<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 头部 -->
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <!-- 列表 -->
      <el-tree
        :data="list"
        :props="defaultProps"
        :default-expand-all="true"
      >
        <template #default="{ data }">
          <el-row
            type="flex"
            justify="space-between"
            align="middle"
            style="height: 40px; width: 100%;"
          >
            <el-col :span="20">
              <span>{{ data.name }}</span>
            </el-col>
            <el-col :span="4">
              <el-row type="flex" justify="end">
                <!-- 两个内容 -->
                <el-col>{{ data.manager }}</el-col>
                <el-col>
                  <!-- 下拉菜单 element -->
                  <el-dropdown>
                    <span> 操作<i class="el-icon-arrow-down" /> </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="addDepart(data.id)">添加子部门</el-dropdown-item>
                      <el-dropdown-item @click.native="editDepart(data.id)">编辑部门</el-dropdown-item>
                      <el-dropdown-item @click.native="delDepartment(data.id)">删除部门</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 添加部门弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      @open="closeAddDialog"
    >
      <template>
        <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
              <el-option v-for="item in peoples" :key="item.id" :label="item.username" :value="item.username" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="dialogVisible= false">取 消</el-button>
        <el-button type="primary" @click="clickSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { delDepartments, getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/department'
import transTree from '@/utils/transTree'
import { getEmployeeSimple } from '@/api/employees'

export default {
  name: 'Department',
  props: {
    curNode: {
      type: Object,
      default() {
        return {}
      }
    }
  },

  data() {
    // 表单自定义验证规则
    const validtateCode = (rule, value, callback) => {
      let codeList = []
      if (this.form.id) {
        codeList = this.sourceList.map(item => item.code)
          .filter(code => code !== this.cacheCode)
      } else {
        codeList = this.sourceList.map((item) => item.code)
      }

      if (codeList.includes(value)) {
        return callback(new Error('code不能重复'))
      } else {
        callback()
      }
    }
    return {
      // 部门列表
      list: [],

      // 部门列表设置
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 弹窗控制
      dialogVisible: false,

      // 表单
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },

      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }

        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validtateCode, message: 'code不能出现重复', trigger: ['blur', 'change'] }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },

      // 负责人列表
      peoples: [],

      curId: '',
      sourceList: [],
      cacheCode: ''
    }
  },
  mounted() {
    this.fetchDepartment()
  },
  methods: {
    // 将获取到的信息传给list
    async fetchDepartment() {
      const res = await getDepartments()
      this.list = transTree(res.depts)
      this.sourceList = res.depts
    },

    // 删除部门
    delDepartment(id) {
      this.$confirm('你确定要删除吗', '温馨提示').then(async() => {
        await delDepartments(id)
        this.$message.success('删除成功')
        this.fetchDepartment()
      })
    },

    // 获取部门管理者
    async hGetEmployeeSimple() {
      const res = await getEmployeeSimple()
      this.peoples = res
    },

    // 当弹窗打开时调用axios
    closeAddDialog() {
      this.hGetEmployeeSimple()
    },

    // 打开弹窗
    addDepart(id) {
      this.dialogVisible = true
      this.curId = id
    },

    // 点击确定添加部门
    clickSubmit() {
      this.$refs.deptForm.validate(async valid => {
        if (valid) {
          // 判断有没有id
          if (this.form.id) {
            // 有id就调用更新接口
            await updateDepartments(this.form)
          } else {
            await addDepartments({ ...this.form, pid: this.curId })
          }

          this.dialogVisible = false
          this.fetchDepartment()
          this.$message.success(`${this.form.id ? '更新成功' : '添加成功'}`)
          this.$refs.deptForm.resetFields()
        }
      })
    },

    // 点击编辑部门
    async editDepart(id) {
      this.dialogVisible = true
      const res = await getDepartDetail(id)
      console.log(res)
      this.form = res
      this.cacheCode = res.code
    }
  }
}
</script>
